package com.liser.southernstar.collection.ui.widget.order;


import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.liser.southernstar.R;
import com.liser.southernstar.collection.model.vo.OrderTypeVO;
import com.liser.southernstar.collection.ui.adapter.OrderItemAdapter;
import com.liser.southernstar.collection.ui.adapter.OrderTypeAdapter;
import com.liser.southernstar.neleme.adapters.FoodAdapter;
import com.liser.southernstar.neleme.utils.ViewUtils;
import com.liser.southernstar.neleme.views.AddGoodsWidget;
import com.liser.southernstar.neleme.views.SimpleDividerDecoration;

public class OrderBodyWidget extends LinearLayout {

    private RecyclerView recyclerView1;

    private RecyclerView recyclerView2;

    private LinearLayoutManager linearLayoutManager;

    public OrderTypeAdapter orderTypeAdapter;

    public OrderItemAdapter orderItemAdapter;

    private boolean move;

    private int index;

    private Context mContext;

    private TextView tvStickyHeaderView;

    private View stickView;

    public OrderBodyWidget(Context context) {
        super(context);
    }

    public OrderBodyWidget(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        inflate(mContext, R.layout.widget_order_body, this);
        initViews();
        initRecyclerView();
        initOnItemTouchListener();
        initOrderItemListener();
    }

    private void initViews() {
        recyclerView1 = findViewById(R.id.recycler1);
        recyclerView2 = findViewById(R.id.recycler2);
        stickView = findViewById(R.id.stick_header);
        tvStickyHeaderView = findViewById(R.id.tv_header);
    }

    private void initRecyclerView() {
        recyclerView1.setLayoutManager(new LinearLayoutManager(mContext));
        orderTypeAdapter = new OrderTypeAdapter();
        View view = new View(mContext);
        view.setMinimumHeight(ViewUtils.dip2px(mContext, 50));
        orderTypeAdapter.addFooterView(view);
        orderTypeAdapter.bindToRecyclerView(recyclerView1);
        recyclerView1.addItemDecoration(new SimpleDividerDecoration(mContext, R.color.divider_gray));
        recyclerView1.setItemAnimator(null);
        if (recyclerView1.getItemAnimator() != null) {
            ((DefaultItemAnimator) recyclerView1.getItemAnimator()).setSupportsChangeAnimations(false);
        }

        linearLayoutManager = new LinearLayoutManager(mContext);
        recyclerView2.setLayoutManager(linearLayoutManager);
        recyclerView2.addItemDecoration(new SimpleDividerDecoration(mContext, R.color.divider_gray));
        if (recyclerView2.getItemAnimator() != null) {
            ((DefaultItemAnimator) recyclerView2.getItemAnimator()).setSupportsChangeAnimations(false);
        }
        orderItemAdapter = new OrderItemAdapter();
        View view2 = new View(mContext);
        view2.setMinimumHeight(ViewUtils.dip2px(mContext, 50));
        orderItemAdapter.addFooterView(view2);
        orderItemAdapter.bindToRecyclerView(recyclerView2);
    }

    private void initOnItemTouchListener() {
        recyclerView1.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                if (recyclerView2.getScrollState() == RecyclerView.SCROLL_STATE_IDLE) {
                    orderTypeAdapter.fromClick = true;
                    orderTypeAdapter.setChecked(i);
                    String type = view.getTag().toString();
                    for (int ii = 0; ii < orderTypeAdapter.getData().size(); ii++) {
                        OrderTypeVO orderTypeVO = orderTypeAdapter.getData().get(ii);
                        if (orderTypeVO.getName().equals(type)) {
                            index = ii;
                            moveToPosition(index);
                            break;
                        }
                    }
                }
            }
        });

        recyclerView2.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemChildClick(adapter, view, position);
                /*if (view.getId() == R.id.food_main) {
                    Intent intent = new Intent(mContext, DetailActivity.class);
                    intent.putExtra("food", (FoodBean) adapter.getData().get(position));
                    intent.putExtra("position", position);
                    mContext.startActivity(intent);
                    ((Activity) mContext).overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                }*/
            }

            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {

            }
        });
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initOrderItemListener() {
        recyclerView2.setOnTouchListener((v, event) -> {
            orderTypeAdapter.fromClick = false;
            return false;
        });

        recyclerView2.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (move) {
                    move = false;
                    //获取要置顶的项在当前屏幕的位置，mIndex是记录的要置顶项在RecyclerView中的位置
                    int n = index - linearLayoutManager.findFirstVisibleItemPosition();
                    if (0 <= n && n < recyclerView.getChildCount()) {
                        //获取要置顶的项顶部离RecyclerView顶部的距离
                        int top = recyclerView.getChildAt(n).getTop();
                        //最后的移动
                        recyclerView.smoothScrollBy(0, top);
                    }
                } else {
                    View stickyInfoView = recyclerView.findChildViewUnder(stickView.getMeasuredWidth() / 2, 5);
                    if (stickyInfoView != null && stickyInfoView.getContentDescription() != null) {
                        tvStickyHeaderView.setText(String.valueOf(stickyInfoView.getContentDescription()));
                        orderTypeAdapter.setType(String.valueOf(stickyInfoView.getContentDescription()));
                    }

                    View transInfoView = recyclerView.findChildViewUnder(stickView.getMeasuredWidth() / 2, stickView.getMeasuredHeight() + 1);
                    if (transInfoView != null && transInfoView.getTag() != null) {
                        int transViewStatus = (int) transInfoView.getTag();
                        int dealtY = transInfoView.getTop() - stickView.getMeasuredHeight();
                        if (transViewStatus == FoodAdapter.HAS_STICKY_VIEW) {
                            if (transInfoView.getTop() > 0) {
                                stickView.setTranslationY(dealtY);
                            } else {
                                stickView.setTranslationY(0);
                            }
                        } else if (transViewStatus == FoodAdapter.NONE_STICKY_VIEW) {
                            stickView.setTranslationY(0);
                        }
                    }
                }
            }
        });
    }

    private void moveToPosition(int n) {
        //先从RecyclerView的LayoutManager中获取第一项和最后一项的Position
        int firstItem = linearLayoutManager.findFirstVisibleItemPosition();
        int lastItem = linearLayoutManager.findLastVisibleItemPosition();
        //然后区分情况
        if (n <= firstItem) {
            //当要置顶的项在当前显示的第一个项的前面时
            recyclerView2.scrollToPosition(n);
        } else if (n <= lastItem) {
            //当要置顶的项已经在屏幕上显示时
            int top = recyclerView2.getChildAt(n - firstItem).getTop();
            recyclerView2.scrollBy(0, top);
        } else {
            //当要置顶的项在当前显示的最后一项的后面时
            recyclerView2.scrollToPosition(n);
            //这里这个变量是用在RecyclerView滚动监听里面的
            move = true;
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    public void setAddClick(AddGoodsWidget.OnAddClick onAddClick) {
        orderItemAdapter.setOnAddClick(onAddClick);
    }
}
